package com.shloma.bbts.channel.impl.yt;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.shloma.bbts.channel.Encoder;
import com.shloma.bbts.stream.yt.RootElement;

public abstract class BaseEncoder implements Encoder {

	@Override
	public byte[] encode(RootElement pkg, Class<?> pkgType) {
		ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();

		try {
			JAXBContext cxt = JAXBContext.newInstance(pkgType);
			Marshaller marshaller = cxt.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			marshaller.marshal(pkg, byteArrayOS);

			byte[] pkgData = byteArrayOS.toByteArray();
			printResult(pkgData);

			return pkgData;
		} catch (JAXBException exception) {
			printError(exception);
			throw new RuntimeException(exception);
		} finally {
			if (byteArrayOS != null) {
				try {
					byteArrayOS.close();
				} catch (IOException e) {
					printError(e);
				}
			}
		}
	}

	public abstract void printResult(byte[] pkgData);

	public abstract void printError(Throwable throwable);
}
